<template>
  <div class="goods-image">
    <div
      class="large"
      :style="{
        backgroundImage: `url(${images[currentIndex]})`,
        backgroundPositionX: bgPosition.x,
        backgroundPositionY: bgPosition.y,
      }"
      v-show="show"
    ></div>
    <div class="middle" ref="target">
      <img :src="images[currentIndex]" alt="" />
      <div
        class="layer"
        v-show="show"
        :style="{
          left: `${layerPositions.left}px`,
          top: `${layerPositions.top}px`,
        }"
      ></div>
    </div>
    <ul class="small">
      <li
        v-for="(item, index) in images"
        :key="item"
        @mouseenter="currentIndex = index"
        :class="{ active: currentIndex === index }"
      >
        <img :src="item" alt="" />
      </li>
    </ul>
  </div>
</template>
<script>
import { ref, watch } from "vue";
import { useMouseInElement } from "@vueuse/core";

export default {
  name: "GoodsImages",
  props: {
    images: {
      type: Array,
      default: () => [],
    },
  },
  setup() {
    const currentIndex = ref(0);
    // 控制大图容器和镜片显示
    const show = ref(false);
    // 容器dom
    const target = ref();
    const { elementX, elementY, isOutside } = useMouseInElement(target);
    // 控制镜片位置
    const layerPositions = ref({ left: 0, top: 0 });
    // 用于控制大图位置
    const bgPosition = ref({ x: 0, y: 0 });
    // 监听 鼠标和元素之间的关系的变化
    watch([elementX, elementY, isOutside], ([x, y, isOutside]) => {
      if (isOutside) {
        // 鼠标移出
        show.value = false;
      } else {
        // 鼠标移入
        show.value = true;
        // 控制镜片位置
        layerPositions.value = {
          left: x - 100 < 0 ? 0 : x - 100 > 200 ? 200 : x - 100,
          top: y - 100 < 0 ? 0 : y - 100 > 200 ? 200 : y - 100,
        };
        // 控制大图
        bgPosition.value = {
          x: -layerPositions.value.left * 2 + "px",
          y: -layerPositions.value.top * 2 + "px",
        };
      }
    });

    return { currentIndex, show, target, layerPositions, bgPosition };
  },
};
</script>
<style scoped lang="less">
.goods-image {
  width: 480px;
  height: 400px;
  position: relative;
  display: flex;
  z-index: 500;
  .large {
    position: absolute;
    top: 0;
    left: 412px;
    width: 400px;
    height: 400px;
    box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
    background-repeat: no-repeat;
    background-size: 800px 800px;
    background-color: #f8f8f8;
  }
  .middle {
    width: 400px;
    height: 400px;
    background: #f5f5f5;
    position: relative;
    cursor: move;
    .layer {
      width: 200px;
      height: 200px;
      background: rgba(0, 0, 0, 0.2);
      left: 0;
      top: 0;
      position: absolute;
    }
  }
  .small {
    width: 80px;
    li {
      width: 68px;
      height: 68px;
      margin-left: 12px;
      margin-bottom: 15px;
      cursor: pointer;
      &:hover,
      &.active {
        border: 2px solid @xtxColor;
      }
    }
  }
}
</style>
